package com.lagou.edu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.MalformedURLException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
public class LimitRegisterFilter  implements GlobalFilter, Ordered {
    @Value("${ipCount}")
    private Integer ipCount;

    private static Map<String, AtomicInteger> ipCountMap = new ConcurrentHashMap<>();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从上下文中取出request和response对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = null;
        try {
            path = request.getURI().toURL().getPath();
            if (path.contains("register")) {
                //可以用redis实现
                //如果访问的是注册接口
                String clientIp = request.getRemoteAddress().getHostString();
                AtomicInteger atomicInteger = ipCountMap.get(clientIp);
                if (atomicInteger == null) {
                    atomicInteger = new AtomicInteger(1);
                    ipCountMap.put(clientIp,atomicInteger);
                }else{
                    int count = atomicInteger.incrementAndGet();
                    if(count > ipCount){
                        response.setStatusCode(HttpStatus.FORBIDDEN); // 状态码
                        String data = "达到注册上限，禁止注册!";
                        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                        return response.writeWith(Mono.just(wrap));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
